<?php

defined('SLP_ROOT') or die("You've not access to this page");

/** 
* Simple Light Php Framework Session Class
* @package		Slp
* @author    	Marc PEPIN
*/ 

class Slp_Session {
	
	
	/**
	* instance of Slp_Session
	* @var Slp_Session
	*/
	
	static private $instance = NULL;
	
	
	/**
	* session data
	* @var array
	*/
	
	private $data = NULL;
	
	
	/**
	* File instance
	* @var Slp_File
	*/
	
	private $file;
	
	
	/**
	* get Slp_Session instance 
	*/
	
	static public function getInstance() {
		if (!self::$instance)
			self::$instance = new Slp_Session;
		return self::$instance;
	}
	
	
	/**
	* Constructor
	*/
	
	public function __construct() {
		
		$this->file = Slp::getInstance()->loadClass("Slp_File", array(SLP_ROOT.'/data.session')); 
		if (!$this->getId()) {
			$id = $this->generateId();
			setcookie("slp_session_id", $id, time() + 365*24*3600, null, null, false, true);
		}
	
		$this->loadData();
	}
	
	
	/**
	* Set sesion data
	* @var string 
	* @var mixed
	*/
	
	public function set($key, $val) {
		$this->data[$this->getId()][$key] = $val;
	}
	
	
	/**
	* get sesion data
	* @var string 
	* @var mixed
	*/
	
	public function get($key, $default= NULL) {
		if (!isset($this->data[$this->getId()][$key]))
			return $default;
		return $this->data[$this->getId()][$key];
	}
	
	
	/**
	* Clear sesion data
	* @var string 
	*/
	
	public function clear($key) {
		if (isset($this->data[$this->getId()][$key]))
			unset($this->data[$this->getId()][$key]);
	}
	
	
	/**
	* load session data
	*/
	
	private function loadData() {
		$data = $this->file->readAll();
		$this->data = !$data ? array() : unserialize($data);
	}
	
	
	/**
	* get session id
	*/
	
	public function getId() {
		if (@!isset($_COOKIE['slp_session_id']))
			return NULL;
		return $_COOKIE['slp_session_id'];
	}
	
	
	/**
	* generate session id
	*/
	
	private function generateId(){
		return uniqid(md5("slp_session_id"));
	}
	
	
	/**
	* Destructor
	*/
	
	public function __destruct() {
		$this->file->write(serialize($this->data));	
	}
}


?>